﻿import Taro, { Component } from '@tarojs/taro'
import { Swiper, SwiperItem, Image, View, Text, RichText,  Button } from '@tarojs/components'
import '../../assets/common.scss'
import CommonJs from '../../utils/common'
import './pkgodetails.scss'

export default class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      content:{},//商品信息
      pic:[],//商品轮播图片
      photoList:{},//商品详情图片长图
      specificationsList:[],
      isload:0,//判断页面是否加载完成
      alertnum:0,
      resultnum:1,
      indexs:0,
      amount: 0,
      specSerial: '',
      mallPrice: '',
      shareUid: '',
      originalprice:''
    }
  }
  config = {
    navigationBarTitleText: '加载中'
  }

  componentWillMount () {
    var _this = this
    var str = _this.$router.preload.str
    // console.log(JSON.stringify(str)+'1111111111111111111111111111111')
    var strs = str.split('_')
    _this.getdata(strs[0],strs[1])
    _this.getphoto(strs[0])
    _this.getspecifications(strs[0],strs[1],1)
  }

  componentDidMount () {
  }

  componentWillUnmount () { }

  componentDidShow () {}

  componentDidHide () { }

  opendetails(url){
    var _this = this
    var specificationsList = _this.state.specificationsList
    var aar = []
    var obj = {}
    obj.id = specificationsList.goodsInventoryResult.id
    obj.logo = specificationsList.shopCommodity.logo
    obj.commodityName = specificationsList.shopCommodity.commodityName
    obj.price = _this.state.mallPrice
    obj.amount = _this.state.resultnum
    obj.goodsName = _this.state.specSerial
    obj.dealerId = specificationsList.shopCommodity.dealerId
    obj.dealerName = specificationsList.shopCommodity.dealerName
    obj.shopId = specificationsList.shopCommodity.shopId
    obj.shopName = specificationsList.shopCommodity.shopName
    obj.commodityId = specificationsList.shopCommodity.commodityId
    obj.needToDistribute = specificationsList.shopCommodity.needToDistribute
    aar.push(obj)
    _this.setState({
      alertnum:0
    })
    // console.log(JSON.stringify(aar))
    _this.$preload({
      aar: aar
    })
    CommonJs.openTo(url)
  }
  
  open(url){
    CommonJs.open(url);
  }
  getdata(commodityId,shopId){
    //商品详情
    var _this=this
    //console.log(JSON.stringify(_this.$router)+'2222222222')
    //commodityId:_this.$router.preload.commodityId,
    //shopId:_this.$router.preload.shopId
    var date = {
      commodityId:commodityId,
      shopId:shopId
    }
    CommonJs.ajaxRequest('/shop/getShopCommodityByCommodityIdAndShopId',date,'GET',function(res){
      // console.log(JSON.stringify(res)+'2222222222')
      Taro.setNavigationBarTitle({title:"商品详情"})
      _this.setState({
        content: res.content,
        isload: 1
      })
    })
  }
  getphoto(id){
    //获取详情长图
    var _this=this
    //id:_this.$router.preload.commodityId,
    var date = {
      id:id,
      roleTypeId:1003
    }
    CommonJs.ajaxRequest('/commodity/getDetail',date,'GET',function(res){
      // console.log(JSON.stringify(res)+'6666666666777777777777')
      var pic = []
      var img = res.content.content
      var imgs = img.replace(/\<img/g, '<img style="width:100%;height:auto;display:block"')
      // console.log(JSON.stringify(imgs)+'111111111111111111')
      if (imgs.indexOf(',') > 0) {
        pic = imgs.split(',')
      } else {
        pic.push(imgs)
      }
      _this.setState({
        pic: pic,
        photoList: res.content
      })
    })
  }
  getspecifications(commodityId,shopId,type){
    //商品价格
    var _this=this;
    var date = {
      commodityId:commodityId,
      shopId:shopId
    }
    ///commodity/getGoodsInventories
    CommonJs.ajaxRequest('/shop/getRelevantInforOfSpec',date,'GET',function(res){
      // console.log(JSON.stringify(res)+'6666666666777777777777')
      var specSerial = ''
      var alertnum = 0
      var specSerials = res.content.goodsInventoryResult.specSerial
      if (specSerials.indexOf(':') != -1) {
        specSerial = specSerials.split(':')[1]
      } else {
        specSerial = specSerials
      }
      // console.log(specSerial)
      if (type == 1) {
        alertnum = 0
      } else if (type == 2) {
        alertnum = 1
      }
      // console.log(alertnum+'///111111111111')
      _this.setState({
        specificationsList: res.content,
        alertnum: alertnum,
        amount: res.content.goodsInventoryResult.amount,
        specSerial: specSerial,
        mallPrice: res.content.goodsInventoryResult.mallPrice,
        originalprice: res.content.goodsInventoryResult.originalprice,
        indexs: 0
      })
    },'','','hideLoad')
  }
  
  openalert(){
    var _this=this
    var content = _this.state.content
    _this.getspecifications(content.commodityId,content.shopId,2)
  }
  openaddclass(index, specSerial){
    var _this = this
    _this.setState({
      indexs:index,
      specSerial: specSerial
    })
    _this.countPM(specSerial)
  }
  closealert(){
    var _this=this;
    _this.setState({
      alertnum: 0
    })
  }
  reducenum(){
    var _this=this;
    var resultnum = _this.state.resultnum;
    resultnum = resultnum - 1;
   if(resultnum<=0){
    Taro.showToast({
      title:'亲，至少也要买一件哦~~',
      icon: 'none',
      duration: 2000
    });
    return;
   }
    _this.setState({
      resultnum: resultnum
    });
  }
  addnum(){
    var _this=this;
    var resultnum = _this.state.resultnum;
    resultnum = resultnum + 1;
    var amount = _this.state.amount;
    if(resultnum>amount){
      Taro.showToast({
      title:'亲，已超过库存数量哦~~',
      icon: 'none',
      duration: 2000
    });
    return;
    }
    _this.setState({
        resultnum: resultnum
      });
  }
  preventTouchMove(event){
    //自定义弹窗防止出现蒙层还可以滑动
    event.stopPropagation()
  }
  countPM(specSerial){
    var _this=this
    var content = _this.state.content
    var date = {
      commodityId: content.commodityId,
      shopId: content.shopId,
      dealerId: content.dealerId,
      roleTypeId: 1003,
      specSerial: specSerial
    }
    CommonJs.ajaxRequest('/commodity/getGoodsInventoryResultBySpecSerial',date,'GET',function(res){
        // console.log(JSON.stringify(res)+'666666666wwwwwwwwww7')
        if (res) {
          _this.setState({
            amount: res.content.amount,
            mallPrice: res.content.mallPrice
          })
        }
    })
  }
  render () {
    const specificationsList = this.state.specificationsList
    const pic = this.state.pic
    let conten = this.state.photoList.content
    let contentt = String(conten)
    let contents = contentt.replace(/\<img/g, '<img style="width:100%;height:auto;display:block"')
    //原来的返回
    // <View className='qun-back' onClick={this.opendetails.bind(this,'/pages/activity/activity','')}><Image className='qun-backimg' src={backwmall}></Image></View>
    return (
      <View className='page' style={this.state.isload == 1 ? 'display:block;' : 'display:none;'}>
        <View className='banner'>
          <View className='qun-bg'>
            <Swiper className='qun-swiper' indicatorDots='true'  autoplay='true'>
              <SwiperItem>
                <Image className='qun-pic' src={content.logo}></Image>
              </SwiperItem>
              {pic.map((item, index) => (
              <SwiperItem>
                <RichText nodes={item}></RichText>
              </SwiperItem>
              ))}
            </Swiper>
            <View className='qun-name'>{content.commodityName}</View>
            <View className='qun-name qun-snames'>{content.summary}</View>
            <View className='qun-name'>
              <Text decode='true' className='qun-shop'>零售价：
                <Text decode='true' className='qun-price'>￥{this.state.mallPrice}</Text>
              </Text>
              <Text decode='true' className='qun-original'>原价：￥{this.state.originalprice}</Text>
            </View>
          </View>
          <View className='qun-details'>
            <View className='details-title'>商品详情</View>
            <View className='qun-photo'><RichText nodes={contents}></RichText></View>
          </View>
          <View className='qun-buys'>
            <View onClick={this.openalert.bind()} className='now-buys'>立即购买</View>
          </View>
        </View>
        <View className='specifications' style={this.state.alertnum == 1?'display:block':'display:none'} onTouchmove={this.preventTouchMove.bind(this)}>
          <View className='specifications-con'>
            <View className='specifications-close' onClick={this.closealert.bind()}>X</View>
            <View className='specifications-title'>
              <View className='specifications-photo'>
                <Image className='specifications-pic' src={specificationsList.shopCommodity.logo}></Image>
              </View>
              <View className='specifications-name'>
                <View className='specifications-bname'>{specificationsList.shopCommodity.commodityName}</View>
                <View className='specifications-sname'>{specificationsList.shopCommodity.summary}</View>
                <View className='specifications-money'>{this.state.mallPrice}元</View>
              </View>
            </View>
            <View className='specifications-change'>
              {specificationsList.specInfor.map((item, index) => (
              <View>
                <View className='specifications-nav'>选择{item.availableSpecification == '统一规格' ? item.availableSpecification : '规格'}</View>
                <View className='specifications-changecon'>
                  {item.availableSpecification != '统一规格' ? 
                    item.availableSpecificationValue.map((item1, index1) => (
                      <Text className={this.state.indexs == index1?"specifications-active":"specifications-class"} onClick={this.openaddclass.bind(this,index1,item1)}>{item1}</Text>
                    )) 
                    : 
                    <Text className='specifications-active'>统一规格</Text>
                }
                </View>
              </View>
              ))}
              <View className='specifications-num'>
                <Text className='specifications-nums'>数量</Text>
                <View className='specifications-reduce' onClick={this.reducenum.bind()}>-</View>
                <View className='specifications-val'>{this.state.resultnum}</View>
                <View className='specifications-reduce' onClick={this.addnum.bind()}>+</View>
                <Text className='specifications-stock'>库存 <Text className='stock-num'>{this.state.amount}</Text></Text>
              </View>
              <View className='specifications-buy' onClick={this.opendetails.bind(this,'/pages/pkgo/confirmorder')}>立即购买</View>
            </View>
          </View>
        </View>
      </View>
    )
  }
}